package com.spzx.rabbit.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * @author : 戚欣扬
 * @Description :
 */
@Slf4j
@Component
public class RabbitInitConfigApplicationListener implements ApplicationListener<ApplicationReadyEvent> {
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        this.setupCallbacks();
    }

    private void setupCallbacks() {
        rabbitTemplate.setConfirmCallback((correlationData, ack, reason) -> {
            if (ack) {
                log.info("消息发送到Exchange成功：{}", correlationData);
            } else {
                log.error("消息发送到Exchange失败：{}", reason);
            }
        });
        rabbitTemplate.setReturnsCallback(returned -> {
            log.error("返回: " + returned.getMessage()
                    + "\n 响应码: " + returned.getReplyCode()
                    + "\n 响应消息: " + returned.getReplyText()
                    + "\n 交换机: " + returned.getExchange()
                    + "\n 路由: " + returned.getRoutingKey());
        });
    }
}


